package com.feeyo.groundservice.recordnfc.viewmodel

import android.app.Application
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.feeyo.groundservice.base_util.CallbackWithData
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.formatTimeYMD
import com.feeyo.groundservice.base_util.getStartEndTime
import com.feeyo.groundservice.http.utils.NetClientUtil
import com.feeyo.groundservice.http.utils.getData
import com.feeyo.groundservice.recordnfc.activity.NfcLogActivity
import com.feeyo.groundservice.recordnfc.base.GlobalHandler
import com.feeyo.groundservice.recordnfc.base.MyBaseObserver
import com.feeyo.groundservice.recordnfc.base.MyOkhttpClient
import com.feeyo.groundservice.recordnfc.constant.AttachResourceType
import com.feeyo.groundservice.recordnfc.constant.RecorderType
import com.feeyo.groundservice.recordnfc.constant.baseUrl
import com.feeyo.groundservice.recordnfc.constant.currentSite
import com.feeyo.groundservice.recordnfc.constant.uid
import com.feeyo.groundservice.recordnfc.constant.unitList
import com.feeyo.groundservice.recordnfc.model.GateItemBO
import com.feeyo.groundservice.recordnfc.model.MixNfcTypeBO
import com.feeyo.groundservice.recordnfc.model.NfcBindBO
import com.feeyo.groundservice.recordnfc.model.NfcBindItemBO
import com.feeyo.groundservice.recordnfc.model.NfcCarBO
import com.feeyo.groundservice.recordnfc.model.NfcLogBO
import com.feeyo.groundservice.recordnfc.model.NfcLogItemBO
import com.feeyo.groundservice.recordnfc.model.NfcUserBO
import com.feeyo.groundservice.recordnfc.model.ParkingBO
import com.feeyo.groundservice.recordnfc.model.ParkingItemBO
import com.feeyo.groundservice.recordnfc.model.TaskBO
import com.feeyo.groundservice.recordnfc.model.TaskItemBO
import com.feeyo.groundservice.recordnfc.model.UnitItemBO
import com.feeyo.groundservice.recordnfc.model.api.RecorderCardApi
import kotlinx.coroutines.launch

/**
 *作者：70893 on 2025-10-07
 *描述：
 */
internal class RecorderCardViewModel(private val myApp: Application) : AndroidViewModel(myApp) {

    val userList = mutableStateOf<List<NfcUserBO>?>(null)
    val carList = mutableStateOf<List<NfcCarBO>?>(null)
    val taskList = mutableStateOf<List<TaskItemBO>?>(null)
    val parkingList = mutableStateOf<List<ParkingItemBO>?>(null)
    val gateList = mutableStateOf<List<GateItemBO>?>(null)

    val nfcBindList = mutableStateOf<List<NfcBindItemBO>?>(null)

    val nfcLogList = mutableStateOf<List<NfcLogItemBO>?>(null)


    /**保障单位**/
    fun getUnitList() {
        val map = hashMapOf<String, Any>()
        viewModelScope.launch {
            getData(
                requestCode = {
                    val unitList =
                        getClient().getRetrofit(baseUrl).create(RecorderCardApi::class.java)
                            .getUnitList()
                    it.emit(unitList)
                },
                object : MyBaseObserver<List<UnitItemBO>>(msg = "查询中...", silence = true) {
                    override fun onSuccess(data: List<UnitItemBO>?) {
                        super.onSuccess(data)
                        data?.let {
                            //全局存一下
                            unitList.apply {
                                clear()
                                addAll(it.filter { it.iata == currentSite })
                                //临时加上全部
                                add(0, UnitItemBO("", "全部", ""))
                            }
                        }
                    }
                }
            )
        }
    }

    /**根据关键词搜索用户**/
    fun getUserList(searchItem: String, unitId: String) {

        val map = hashMapOf<String, Any>().apply {
            if (searchItem.isNotEmpty()) {
                this["search_item"] = searchItem
            }
            this["size"] = 1000
            this["unit_id"] = listOf(unitId)
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val userList = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .getUserList(map)
                    it.emit(userList)
                },
                object : MyBaseObserver<List<NfcUserBO>>(msg = "查询中...", silence = false) {
                    override fun onSuccess(data: List<NfcUserBO>?) {
                        super.onSuccess(data)
                        userList.value = data
                    }
                }
            )
        }
    }

    /**根据关键词搜索车辆**/
    fun getCarList(searchItem: String, unitId: String) {

        val map = hashMapOf<String, Any>().apply {
            if (searchItem.isNotEmpty()) {
                this["search_item"] = searchItem
            }
            this["size"] = 500
            this["unit_id"] = listOf(unitId)
        }
        viewModelScope.launch {
            getData(
                requestCode = {
                    val carList = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .getCarList(map)
                    it.emit(carList)
                },
                object : MyBaseObserver<List<NfcCarBO>>(msg = "查询中...", silence = false) {
                    override fun onSuccess(data: List<NfcCarBO>?) {
                        super.onSuccess(data)
                        carList.value = data
                    }
                }
            )
        }
    }


    /**任务列表**/

    fun getTaskList(key: String, unitId: String, oldData: List<String>) {

        val map = HashMap<String, Any>().apply {
            this["limit"] = 500
            this["page"] = 1
            if (key.isNotEmpty()) {
                this["keyword"] = key
            }
            this["unit_id_list"] = if (unitId.isEmpty()) listOf<String>() else listOf(unitId)
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val taskList = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .getTaskList(map)
                    it.emit(taskList)
                },
                object : MyBaseObserver<TaskBO>(msg = "查询中...", silence = false) {
                    override fun onSuccess(data: TaskBO?) {
                        super.onSuccess(data)
                        taskList.value = data?.data?.onEach {
                            it.task_config.checked.value = it.task_config.id in oldData
                        }
                    }
                }
            )
        }
    }

    /**机位列表
     * @param key 机位名称
     * **/
    fun getParkingList(key: String) {
        val map = HashMap<String, Any>().apply {
            this["limit"] = 500
            this["page"] = 1
            if (key.isNotEmpty()) {
                this["title"] = key
            }
            this["iata"] = currentSite
        }


        viewModelScope.launch {
            getData(
                requestCode = {
                    val parkingList = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .getParkingList(map)
                    it.emit(parkingList)
                },
                object : MyBaseObserver<ParkingBO>(msg = "查询中...", silence = true) {
                    override fun onSuccess(data: ParkingBO?) {
                        super.onSuccess(data)
                        parkingList.value = data?.data
                    }
                }
            )
        }
    }

    /**登机口列表**/
    fun getGateList(key: String) {

        val map = HashMap<String, Any>().apply {
            if (key.isNotEmpty()) {
                this["title"] = key
            }
            this["iata"] = currentSite
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val gateList = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .getGateList(map)
                    it.emit(gateList)
                },
                object : MyBaseObserver<List<GateItemBO>>(msg = "查询中...", silence = true) {
                    override fun onSuccess(data: List<GateItemBO>?) {
                        super.onSuccess(data)
                        gateList.value = data
                    }
                }
            )
        }
    }

    /**更新用户信息
     *
     * @param uid
     * @param nfcId
     * @param force 是否强制更新 1强制 0不强制
     * @param type 1:查询模式 0是更新模式
     *
     * **/
    fun updateUserInfo(
        uid: String,
        nfcId: String,
        force: Int? = null,
        type: Int,
        listener: SuccessCallback
    ) {

        val map = HashMap<String, Any>().apply {
            this["uid"] = uid
            this["nfc_id"] = nfcId

            force?.let {
                this["force"] = it
            }
            this["type"] = type
            this["iata"] = currentSite
        }
        viewModelScope.launch {
            getData(
                requestCode = {
                    val updateUser = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .updateUser(map)
                    it.emit(updateUser)
                },
                object : MyBaseObserver<Any>(msg = "更新中...", silence = false) {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }
    }

    /**更新车辆信息
     *
     * @param carId
     * @param nfcId
     * @param force 是否强制更新 1强制 0不强制
     * @param type 1:查询模式 0是更新模式
     *
     * **/
    fun updateCarInfo(
        carId: String,
        nfcId: String,
        force: Int? = null,
        type: Int,
        listener: SuccessCallback
    ) {

        val map = HashMap<String, Any>().apply {
            this["id"] = carId
            this["nfc_id"] = nfcId
            force?.let {
                this["force"] = it
            }
            this["type"] = type
            this["iata"] = currentSite
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val updateCar = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .updateCar(map)
                    it.emit(updateCar)
                },
                object : MyBaseObserver<Any>(msg = "更新中...", silence = false) {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }
    }


    /**更新任务信息
     *
     *@param taskId 任务id
     * @param nfcId nfcId
     * @param attachResourceType 附带资源类型 目前就是 机位 登机口
     * @param attachResourceName 附带资源名称
     * @param append 是否追加
     * @param listener
     *
     * **/
    fun updateTaskInfo(
        taskId: List<String>,
        nfcId: String,
        attachResourceType: AttachResourceType,
        attachResourceName: String,
        listener: SuccessCallback,
        append: Boolean = false,
    ) {
        val map = HashMap<String, Any>().apply {
            this["task_id"] = taskId
            this["nfc"] = nfcId
            this["nfc_type"] = "task"//nfc类型 user car task，此接口仅使用task即可
            this["title"] = attachResourceName//机位 登机口名称
            this["category"] = when {// 0不限 1机位 2登机口
                attachResourceName.isEmpty() -> 0
                else -> attachResourceType.type
            }
            if (append) {
                this["append"] = true//在原来的卡上追加任务
            }
            this["iata"] = currentSite
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val updateTask = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .updateParkingNfc(map)
                    it.emit(updateTask)
                },
                object : MyBaseObserver<Any>(msg = "更新中...", silence = false) {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }
    }

    /**查询nfc绑定的类型**/
    fun queryNfcBindType(nfcId: String, listener: CallbackWithData<MixNfcTypeBO>) {

        val map = hashMapOf<String, Any>().apply {
            this["id"] = nfcId
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val queryNfcBindType = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .queryNfcBindType(map)
                    it.emit(queryNfcBindType)
                },
                object : MyBaseObserver<MixNfcTypeBO>(msg = "查询中...", silence = true) {
                    override fun onSuccess(data: MixNfcTypeBO?) {
                        super.onSuccess(data)
                        data?.let { listener.success(it) }
                    }
                }
            )
        }
    }


    /**nfc管理**/
    fun getNfcBind(searchKey: String? = null, nfcType: RecorderType? = null) {

        val map = hashMapOf<String, Any>().apply {
            this["page"] = 1
            this["limit"] = 100
            this["page_id"] = 0//不分页
            this["biz"] = hashMapOf<String, Any>().apply {
                this["title"] = searchKey ?: ""
                this["iata"] = currentSite
                this["nfc_type"] = nfcType?.type ?: ""
            }
        }


        viewModelScope.launch {
            getData(
                requestCode = {
                    val getNfcBind = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .getNfcBind(map)
                    it.emit(getNfcBind)
                },
                object : MyBaseObserver<NfcBindBO>(msg = "查询中...", silence = !NfcLogActivity.showLoading) {
                    override fun onSuccess(data: NfcBindBO?) {
                        super.onSuccess(data)
                        nfcBindList.value = data?.let {
                            it.data.forEach { item ->
                                item.car = it.car?.firstOrNull { it.id == item.long_id }
                                item.user = it.user?.firstOrNull { it.uid == item.long_id }
                                item.parking = it.parking?.firstOrNull { it.id == item.long_id }
                            }
                            it.data
                        }
                    }
                }
            )
        }
    }


    /**nfc日志**/
    fun getNfcLog() {

        val map = hashMapOf<String, Any>().apply {
            this["link_id"] = uid
            this["link_type"] = "nfc_bind"
            this["page"] = 1
            this["limit"] = 500
            val times = System.currentTimeMillis().formatTimeYMD().getStartEndTime()
            this["start_time"] = times.first()
            this["end_time"] = times.last()
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val getNfcLog = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .getNfcLog(map)
                    it.emit(getNfcLog)
                },
                object : MyBaseObserver<NfcLogBO>(msg = "查询中...", silence = false) {
                    override fun onSuccess(data: NfcLogBO?) {
                        nfcLogList.value = data?.data
                    }
                }
            )
        }
    }

    /**nfc解绑**/
    fun unbindNfc(id: String, listener: SuccessCallback) {
        val map = hashMapOf<String, Any>().apply {
            this["id"] = id
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val unbindNfc = getClient().getRetrofit(baseUrl)
                        .create(RecorderCardApi::class.java)
                        .unbindNfc(map)
                    it.emit(unbindNfc)
                },
                object : MyBaseObserver<Any>(msg = "解绑中...", silence = false) {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }

    }


    private fun getClient(): NetClientUtil = NetClientUtil.init(myApp)
        .setBaseBean(GlobalHandler.baseBean)
        .setLogEnable(true)
        .setAllowDataIsNull(true)
        .setOkhttpClientBuilder(MyOkhttpClient.client)
}